package x.cribug.app.moudles.controller;

import x.cribug.app.common.util.session.SessionUtil;
import x.cribug.common.entity.app.form.UpdateUserForm;
import x.cribug.app.moudles.service.impl.UserServiceImpl;
import x.cribug.common.common.annotation.NeedLogin;
import x.cribug.common.common.exception.ServiceException;
import x.cribug.common.common.util.result.Result;
import x.cribug.common.entity.app.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Api(tags = "用户服务")
@RestController
@Slf4j
@RequestMapping("/api-app/user")
public class UserController {
    @Resource
    private UserServiceImpl userService;

    @ApiOperation("通过微信登录")
    @GetMapping("/wxLogin")
    public Result<User> loginByWx(String code) throws Exception {
        return Result.ok(userService.loginByWeixin(code));
    }

    @ApiOperation("退出登录")
    @NeedLogin
    @DeleteMapping("/logout")
    public Result logout(HttpServletRequest request) {
        SessionUtil.logout(request);
        return Result.ok();
    }

    @ApiOperation("根据token获取用户数据, 并续期token")
    @NeedLogin
    @GetMapping("/getInfoByToken")
    public Result<User> getUserInfo(HttpServletRequest request) throws ServiceException {
        User user = userService.getUser(SessionUtil.getCurrentWxOpenidFromRequest(request));
        SessionUtil.setUserSession(user); // token已经更新
        return Result.ok(user);
    }

    @ApiOperation("更新信息")
    @NeedLogin
    @PutMapping("/syncUserInfo")
    public Result<Object> updateUser(@RequestBody UpdateUserForm form, HttpServletRequest request) throws Exception {
        return Result.ok(userService.updateUser(form, SessionUtil.getCurrentWxOpenidFromRequest(request)));
    }
}
